import GoEasy from 'goeasy';

// 初始化 GoEasy 实例（单例模式）
export const initGoEasy = () => {
  GoEasy.getInstance({
    host: 'hangzhou.goeasy.io', // 服务器地址（根据实际区域选择）
    appkey: 'BC-9772e271f68f4541879841e801c9f973', // GoEasy appkey
    modules: ['pubsub'], // 加载 pubsub 模块（发布/订阅功能）
  });
};

export const connectGoEasy = () => {
  GoEasy.connect({
    onSuccess: () => {
      console.log('GoEasy connect successfully.');
    },
    onFailed: (error: any) => {
      console.log('Failed to connect GoEasy, code:' + error.code + ',error:' + error.content);
      uni.showModal({
        title: error.code.toString(),
        content: error.content,
        showCancel: false,
        duration: 6000,
      });
    },
    onProgress: (attempts: number) => {
      console.log('GoEasy is connecting', attempts);
    },
  });
};

export const subscribeGoEasy = () => {
  const appStore = useAppStore();
  const userStore = useUserStore();

  GoEasy.pubsub.subscribe({
    channel: `${userStore.userInfor.userId}-msg`,
    onMessage: (message: { content: string; channel: string }) => {
      console.log(message.content);
      try {
        // 解析 JSON 消息
        const data = JSON.parse(message.content);
        appStore.setMsgObj(data);
      } catch (error) {
        console.error('JSON 解析失败:', error);
        console.log('原始消息:', message.content);
      }
    },
    onSuccess: () => {
      console.log('订阅成功');
    },
    onFailed: (error: any) => {
      console.log('订阅失败，错误编码：' + error.code + ' 错误信息：' + error.content);
    },
  });
};
